package com.lzy.conf;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class IDAASExceptionAdvice {


    @Autowired
    I18nServiceImpl i18nService;
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult handleError(MethodArgumentNotValidException e){
        List<ObjectError> errors =e.getBindingResult().getAllErrors();
        JSONObject error_json = new JSONObject();
        errors.stream().forEach(x -> {
            FieldError fieldError =  (FieldError) x;
            error_json.set(fieldError.getField(),x.getDefaultMessage());
        });
        return JSONResult.verifyMsg(error_json.toString());
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public JSONResult handleConstraintViolationException(ConstraintViolationException e) {
        List<String> msgList = e.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        return JSONResult.verifyMsg(String.join(",",msgList));
    }
}
